import { ref, onUnmounted, unref, getCurrentInstance, watch, nextTick } from 'vue';
import { ModalMethods, UseModalReturnType } from '../type';
import { getDynamicProps } from '../../../../utils/common';
import { Nullable } from "../../../../types/global";

export function useModal(props: any): UseModalReturnType {
    const modalRef = ref<Nullable<ModalMethods>>(null);
    const currentInstance = getCurrentInstance();

    const getInstance = () => {
        const instance = unref(modalRef.value);
        if (!instance) {
            console.error('useModal instance is undefined!');
        }
        return instance;
    };

    const register = (modalInstance: ModalMethods) => {
        modalRef.value = modalInstance; // 保存弹窗里的方法，后续通过getInstance获取
        currentInstance?.emit('register', modalInstance);
        watch(
            () => props,
            () => {
                props && modalInstance.setProps(getDynamicProps(props));
            },
            {
                immediate: true,
                deep: true,
            }
        );
    };

    const methods: ModalMethods = {
        setProps: (props): void => {
            getInstance()?.setProps(props);
        },
        openModal: () => {
            getInstance()?.openModal();
        },
        closeModal: () => {
            getInstance()?.closeModal();
        },
        setSubLoading: (status) => {
            getInstance()?.setSubLoading(status);
        },
    };

    return [register, methods];
}
